/**
 * API调用组合式函数
 * 封装常用的API调用逻辑
 */

import { ref, type Ref } from 'vue'
import type { ApiResponse } from '@/api'

/**
 * API调用状态
 */
export interface ApiState<T> {
  data: Ref<T | null>
  loading: Ref<boolean>
  error: Ref<string | null>
}

/**
 * 创建API调用状态
 * @returns API状态对象
 */
export function useApi<T = any>(): ApiState<T> {
  const data = ref<T | null>(null) as Ref<T | null>
  const loading = ref<boolean>(false)
  const error = ref<string | null>(null)

  return {
    data,
    loading,
    error,
  }
}

/**
 * 封装GET请求的组合式函数
 * @param apiCall API调用函数
 * @returns API状态和调用函数
 */
export function useGetApi<T = any>(apiCall: () => Promise<ApiResponse<T>>) {
  const { data, loading, error } = useApi<T>()

  /**
   * 执行GET请求
   */
  const execute = async () => {
    loading.value = true
    error.value = null

    try {
      const response = await apiCall()
      data.value = response.data
    } catch (err: any) {
      error.value = err.message || '请求失败'
    } finally {
      loading.value = false
    }
  }

  return {
    data,
    loading,
    error,
    execute,
  }
}

/**
 * 封装POST/PUT请求的组合式函数
 * @param apiCall API调用函数
 * @returns API状态和调用函数
 */
export function useMutationApi<T = any>(apiCall: (data: any) => Promise<ApiResponse<T>>) {
  const { data, loading, error } = useApi<T>()

  /**
   * 执行变更请求
   * @param requestData 请求数据
   */
  const execute = async (requestData?: any) => {
    loading.value = true
    error.value = null

    try {
      const response = await apiCall(requestData)
      data.value = response.data
      return response
    } catch (err: any) {
      error.value = err.message || '请求失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    data,
    loading,
    error,
    execute,
  }
}
